import json

import quart
import quart_cors

from quart import request

app = quart_cors.cors(quart.Quart(__name__), allow_origin="https://chat.openai.com")

_TODOS = {}


@app.post("/todos/<string:username>")
async def add_todo(username: str):
    request = await quart.request.get_json(force=True)
    if username not in _TODOS:
        _TODOS[username] = []
    _TODOS[username].append(request["todo"])
    return quart.Response(response="ok", status=200)


@app.get("/todos/<string:username>")
async def get_todo(username: str):
    request = await quart.request.get_json(force=True)
    return quart.Response(response=json.dumps(_TODOS.get(username, [])), status=200)


@app.delete("/todos/<string:username>")
async def delete_todo(username: str):
    request = await quart.request.get_json(force=True)
    todo_idx = request["todo_idx"]
    if 0 <= todo_idx < len(_TODOS[username]):
        # del _TODOS[username][todo_idx]
        _TODOS[username].pop(todo_idx)
    return quart.Response(response="ok", status=200)


@app.get("/logo.png")
async def plugin_logo():
    return await quart.send_file("logo.png", mimetype="image/png")


@app.get("/.well-known/ai-plugin.json")
async def plugin_manifest():
    host = request.headers["Host"]
    with open("./.well-known/ai-plugin.json") as f:
        manifest = f.read()
        return quart.Response(manifest, mimetype="text/json")


@app.get("/openapi.yaml")
async def openapi_spec():
    host = request.headers["Host"]
    with open("./openapi.yaml") as f:
        spec = f.read()
        return quart.Response(spec, mimetype="text/yaml")


def main():
    app.run(debug=True, host="0.0.0.0", port=5002)


if __name__ == "__main__":
    main()
